<script setup lang='ts'>
import type { OptionsType, PlusColumn } from 'plus-pro-components'

import {
    // useApplyForRelativeSuppliers,
    useGetApplyDetail,
    useGetCategory,
    useGetEnterpriseBrandOptions,
    useGetProvinceCityCounty,
    useGetSupplieByTypeOptions,
    // useRetryApplyForRelativeSuppliers,
    // useGetSupplierOptions,
    useUpdateApplyStatus,
} from '@fl/api/supplier'
import FlUpload from '@fl/components/fl-upload.vue'
import SubmitBtn from '@fl/components/submit-btn.vue'
import { jsonToArray } from '@fl/utils/fn'
import { cascaderValueToString } from '@fl/utils/tree'
import { cloneDeep } from 'lodash-es'

const applyId = defineModel<string>('applyId', { required: true })
const applyType = defineModel<string>('applyType', { required: true })

const applyVisible = defineModel<boolean>('applyVisible', { required: true })

const initialState = {
    authTime: [],
    brandId: [],
    catId: [],
    fileList: [],
    region: [],
    remark: '',
    type: 1,
} as any
const state = ref(cloneDeep(initialState))

const isEdit = computed(() => !!applyId.value)
const dialogTitle = computed(() => applyType.value === '1' ? '新增供应商关联申请' : applyType.value === '2' ? '恢复合作申请' : '审核')
const getEnterpriseBrandParams = computed<string>(() => state.value.supplierId)
// const getSupplierOptionsParams = computed<string>(() => unref(visible) ? '8' : '')
const getSupplierOptionsParams = computed(() => {
    return {
        type: 8,
        visible: unref(applyVisible),
    }
})

const { data: enterpriseBrandData } = useGetEnterpriseBrandOptions(getEnterpriseBrandParams)
const { data: categoryData, isLoading: isGetCategoryLoading } = useGetCategory()
const { isPending, mutate: updateApplyStatus } = useUpdateApplyStatus()
// const { isPending: isApplyForRelativeSuppliersPending, mutate: applyForRelativeSuppliers } = useApplyForRelativeSuppliers()
// const { isPending: isRetryApplyForRelativeSuppliersPending, mutate: retryApplyForRelativeSuppliers } = useRetryApplyForRelativeSuppliers()
const { data: provinceCityCountyData } = useGetProvinceCityCounty()
// const { data: supplierOptionsData, isLoading: isGetSupplierOptionsLoading } = useGetSupplierOptions(getSupplierOptionsParams)
const { data: supplierOptionsData, isLoading: isGetSupplierOptionsLoading } = useGetSupplieByTypeOptions(getSupplierOptionsParams)

const { data: applyDetailData, isLoading: isGetApplyDetailLoading } = useGetApplyDetail(applyId)

const formRef = ref()
const isFormLoading = computed(() => {
    return isGetApplyDetailLoading.value || isGetCategoryLoading.value || isGetSupplierOptionsLoading.value
})
const isSubmitLoading = computed(() => {
    return isPending.value
})
const brandOptions = computed(() => state.value.supplierId ? (enterpriseBrandData.value || []) : [])

const columns: PlusColumn[] = [
    {
        fieldProps: {
            disabled: isEdit.value,
        },
        label: '供应商',
        options: supplierOptionsData as OptionsType,
        prop: 'supplierId',
        valueType: 'select',
    },
    {
        fieldProps: {
            disabled: isEdit.value,
            onChange: (value: string[][]) => {
                state.value.catName = cascaderValueToString(value, {
                    treeData: categoryData.value,
                })
            },
            props: { multiple: true },
        },
        label: '授权品类',
        options: categoryData as OptionsType,
        prop: 'catId',
        valueType: 'cascader',
    },
    {
        fieldProps: {
            disabled: isEdit.value,
            multiple: true,
            onChange: (value: string[]) => {
                state.value.brandName = value.map((item: string) => brandOptions.value.find((option: any) => option.value === item)!.label)
                    .join(',')
            },
        },
        label: '代理品牌',
        options: brandOptions,
        prop: 'brandId',
        valueType: 'select',
    },
    {
        fieldProps: {
            disabled: isEdit.value,
            endPlaceholder: '请选择结束时间',
            startPlaceholder: '请选择开始时间',
            type: 'daterange',
            valueFormat: 'YYYY-MM-DD',
        },
        label: '授权时间',
        prop: 'authTime',
        valueType: 'date-picker',
    },
    {
        fieldProps: {
            disabled: isEdit.value,
        },
        label: '授权地区',
        options: provinceCityCountyData as OptionsType,
        prop: 'region',
        valueType: 'cascader',
    },
    {
        fieldProps: {
            disabled: isEdit.value,
        },
        label: '厂家授权函',
        prop: 'fileList',
    },
    {
        label: '审核处理',
        options: [
            {
                label: '同意申请',
                value: 1,
            },
            {
                label: '拒绝申请',
                value: 2,
            },
        ],
        prop: 'type',
        valueType: 'radio',
    },
    {
        fieldProps: {
            autosize: { maxRows: 4, minRows: 2 },
        },
        hideInForm: computed(() => state.value.type !== 2),
        label: '拒绝理由',
        prop: 'remark',
        valueType: 'textarea',
    },
]

const rules = {
    authTime: [
        {
            message: '请选择授权时间',
            required: true,
            trigger: 'change',
        },
    ],
    brandId: [
        {
            message: '请选择代理品牌',
            required: true,
            trigger: 'change',
        },
    ],
    catId: [
        {
            message: '请选择授权品类',
            required: true,
            trigger: 'change',
        },
    ],
    fileList: [
        {
            message: '请上传厂家授权函',
            required: true,
            trigger: 'change',
        },
    ],
    region: [
        {
            message: '请选择授权地区',
            required: true,
            trigger: 'change',
        },
    ],
    remark: [
        {
            message: '请输入拒绝理由',
            required: true,
            trigger: 'change',
        },
    ],
    supplierId: [
        {
            message: '请选择供应商',
            required: true,
            trigger: 'change',
        },
    ],
    type: [
        {
            message: '请选择审核处理',
            required: true,
            trigger: 'change',
        },
    ],
}

async function onSubmitBtnClick() {
    const valid = await formRef.value.formInstance.validate()
    if (!valid)
        return
    submit()
}

function submit() {
    const { remark, type } = state.value
    updateApplyStatus({ id: applyId.value, remark, type }, {
        onSuccess() {
            ElMessage.success('操作成功')
            applyVisible.value = false
        },
    })
}

function onCancelBtnClick() {
    closed()
}

function closed() {
    applyVisible.value = false
    applyId.value = ''
    applyType.value = ''
}

watch(() => state.value.supplierId, (newValue, oldValue) => {
    if (oldValue || !newValue) {
        state.value.brandId = []
    }
})

watchEffect(() => {
    if (isEdit.value && applyDetailData.value) {
        const data = cloneDeep(applyDetailData.value)
        const fileList = jsonToArray(data.file)
        Object.assign(state.value, data, {
            authTime: [data.startTime, data.endTime],
            brandId: data.brandId && JSON.parse(data.brandId),
            catId: data.catId && JSON.parse(data.catId),
            fileList,
            region: data.region && JSON.parse(data.region),
        })
    }
})
</script>

<template>
    <PlusDialog v-model="applyVisible"
                :title="dialogTitle"
                width="700"
                close-on-press-escape
                @closed="closed"
    >
        <el-skeleton v-if="isFormLoading"
                     animated
        />

        <PlusForm v-else
                  ref="formRef"
                  v-model="state"
                  :columns="columns"
                  :label-width="100"
                  :rules="rules"
                  :has-footer="false"
        >
            <template #plus-field-fileList>
                <FlUpload v-model="state.fileList"
                          tips
                          :disabled="isEdit"
                          accept=".docx,.pdf,.jpg,.jpeg,.png"
                          list-type="text"
                />
            </template>
        </PlusForm>

        <template #footer>
            <div class="mx-auto">
                <el-button @click="onCancelBtnClick">
                    取消
                </el-button>

                <SubmitBtn type="primary"
                           :loading="isSubmitLoading"
                           @click="onSubmitBtnClick"
                >
                    确定
                </SubmitBtn>
            </div>
        </template>
    </PlusDialog>
</template>
